import os
from .models import Task
from cmdb.models import StorageMachine
from datetime import datetime
from django.utils import timezone
from django_redis import get_redis_connection
from minefieldplatform.settings import BASE_DIR
from .ansible_api import AnsibleClient

redis_cli = get_redis_connection('default')


def get_inventory():
    """
    获取主机清单
    :return:
    """
    hosts = StorageMachine.objects.all().values_list('ip', flat=True)
    inventory = ','.join(hosts)
    return inventory


def exec_playbook(redis_key_prefix, task_id):
    """
    执行playbook
    :param redis_key_prefix: Redis Key前缀
    :param task_id 任务id
    :return:
    """
    redis_cli.delete('{}::{}'.format(redis_key_prefix, task_id))
    hosts = Task.objects.get(id=task_id).dest_hosts
    #hosts = StorageMachine.objects.all().values_list('ip', flat=True)
    sources = hosts+',' #如果是ip的话，必须加逗号。不加逗号的话，会被当做是inventory文件处理
    client = AnsibleClient(sources)
    task = Task.objects.get(id=task_id)
    file_name = str(task.id) + '_' + datetime.now().strftime('%Y%m%d%H%M') + '.yml'
    pb_path = os.path.join(BASE_DIR, 'tmp', file_name)
    print(pb_path)
    with open(pb_path, 'w') as f:
        f.write(task.content)
    client.ansible_playbook(redis_key_prefix, task_id,
                            pb_path, extra_vars=None)
    # 任务已经完成，并且任务结果已经存入redis, 再把redis的结果拿出来存入数据
    result = redis_cli.get('{}::{}'.format(redis_key_prefix, task_id))
    # print(result)
    task.result = str(result, encoding='utf8')
    task.status = 1
    #print(task.result)
    task.save()
    return True


def task_execute(task_id):
    """
    执行任务
    :param task_id:
    :return:
    """
    redis_key_prefix = "ark::task"
    task = Task.objects.get(id=task_id)
    exec_playbook(redis_key_prefix, task_id)
    #print("222")
    return '任务发布成功!'
